import 'dart:async';
import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:url_launcher/url_launcher.dart';

enum WebPayResult { success, fail }

class WebPay {
  WebPay._internal();
  factory WebPay() => _instance;
  static final WebPay _instance = WebPay._internal();

  final StreamController<WebPayResult> _payRespStreamController =
      StreamController<WebPayResult>.broadcast();
  AppLifecycleListener? _appLifecycleListener;

  Future<void> pay(String url) async {
    _appLifecycleListener = AppLifecycleListener(onResume: () async {
      var check = await Get.dialog(
          QsDialog.alert("订单是否已完成支付？", confirmText: "已完成", cancelText: "没有"));
      if (check) {
        _payRespStreamController.add(WebPayResult.success);
      } else {
        _payRespStreamController.add(WebPayResult.fail);
      }
    }, onHide: () {
      log("hide");
    });
    launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication);
  }

  Stream<WebPayResult> payResp() {
    return _payRespStreamController.stream;
  }

  close(StreamSubscription? subscription) {
    subscription?.cancel();
    _appLifecycleListener?.dispose();
  }
}
